# 手机端的购物车
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.shortcuts import redirect
from django.urls import reverse
from myadmin.models import Product


def add(request):
    """ 添加 """
    # 尝试从session中获取名字为cart_list的购物车信息，没有返回{}
    cart_list = request.session.get('cartlist', {})

    # 获取要购买的菜品信息
    pid = request.GET.get('pid', None)
    if pid is not None:
        product = Product.objects.get(id=pid).toDict()
        product['num'] = 1

        # 判断购物车中是否有存在的菜品信息
        if pid in cart_list:
            # 存在就加
            # print(123)
            cart_list[pid]['num'] += product['num']
        else:
            # 没有就放入
            # print(456)
            cart_list[pid] = product

        # 将cart_list放入购物车
        request.session['cartlist'] = cart_list
        print(cart_list)

    # 响应购物车json格式的数据
    return JsonResponse({'cartlist': cart_list})


def delete(request):
    """ 删除 """
    # 尝试从session中获取名字为cart_list的购物车信息，没有返回{}
    pid = request.GET.get('pid', None)
    cart_list = request.session.get('cartlist', {})
    del cart_list[pid]

    # 删除后再再放回session中
    request.session['cartlist'] = cart_list
    # 响应购物车json格式的数据
    return JsonResponse({'cartlist': cart_list})


def clear(request):
    """ 清空 """
    request.session['cartlist'] = {}
    # del request.session['cartlist']
    print(request.session['cartlist'])
    # 响应购物车json格式的数据
    return JsonResponse({'cartlist': {}})


def change(request):
    """ 更改 """
    # 尝试从session中获取名字为cart_list的购物车信息，没有返回{}
    cart_list = request.session.get('cartlist', {})
    # 获取要更改的菜品id
    pid = request.GET.get('pid', 0)
    m = int(request.GET.get('num', 1))  # 更改的数量
    if m < 1:
        m = 1

    # 修改数量
    cart_list[pid]['num'] = m
    # 更改后再再放回session中
    request.session['cartlist'] = cart_list

    # 响应购物车json格式的数据
    return JsonResponse({'cartlist': cart_list})
